package com.net.xpay.admin.secutiry;

import com.net.common.model.Result;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.constant.AdminWebConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
  on 06/02/2018.
 * 需要登陆时返回登陆的错误码而不是重定向到页面
 */
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Autowired
    private SecurityHelper securityHelper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
        if (authException instanceof WebInsufficientAuthException) {
            WebInsufficientAuthException wx = (WebInsufficientAuthException) authException;
            securityHelper.sendRestResult(response, new Result(wx.getErrorCode(), wx.getErrorMessage()));
        } else {
            securityHelper.sendRestResult(response, new Result(PoseidonErrorCode.NEED_LOGIN, AdminWebConstant.LOGIN_URL));
        }
    }
}